package com.cdfahe.gms.web.controller;
import java.io.File;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.cdfahe.common.Constants;
import com.cdfahe.common.util.BuildHtmlFile;
import com.cdfahe.common.util.FileUtils;
import com.cdfahe.common.util.StringUtils;
import com.cdfahe.common.util.page.ResultFilter;
import com.cdfahe.gms.aop.SysContent;
import com.cdfahe.gms.mybatis.entity.Drug;
import com.cdfahe.gms.mybatis.entity.DrugExample;
import com.cdfahe.gms.mybatis.entity.Drugtype;
import com.cdfahe.gms.mybatis.entity.News;
import com.cdfahe.gms.service.IDrugService;
import com.cdfahe.gms.service.IDrugTypeService;
import com.cdfahe.gms.service.INewsService;
import com.sun.org.apache.bcel.internal.generic.NEW;

/**
 * 管理员后台管理控制器
 * @author donzell
 * @version 1.0
 */
@Controller("adminManageController")
public class AdminManageController {
	@Autowired
	private INewsService newsService;
	//药品管理模块
	@Autowired
	private IDrugService drugService;
	@Autowired
	private IDrugTypeService drugTypeService;
	
	@RequestMapping(value = "/init")
    public String test(Model model,HttpServletRequest request) {
		System.out.println("222222");
		DrugExample example = new DrugExample();
		example.createCriteria().andIdIsNotNull();
		List<Drug> alldrugs = drugService.selectDrugByExample(example);
//		News  news = newsService.getNewsById(Integer.parseInt(request.getParameter("id")));
		//页面静态化处理
		//生成的文件存放在网站根目录的html/drug/类别id/
		for (Drug drug : alldrugs) {
			File saveDir = new File(request.getSession().getServletContext().getRealPath(Constants.STATIC_DRUG_DIR+drug.getDrugtype()));
			BuildHtmlFile.createProductHtml(drug,"drugview.html", saveDir);
		}
		return "about/about";
    }
	
	@RequestMapping(value = "/todrugmanage")
	 public String toDrugManage(@ModelAttribute ResultFilter<Drug> rf,HttpServletRequest request,Model model) {
		String categoty =  request.getParameter("categoty");
		model.addAttribute("categoty", categoty);
		drugService.listDrugs(rf,Constants.SELECT_ALL_DRUG,10);
		model.addAttribute("rf", rf);
		return "managepages/drugmanage/druglist";
	 }
	
	 @RequestMapping(value = "/todeldrug")
	 public ModelAndView todeldrug(HttpServletRequest request,Model model) {
		 String drugid =  request.getParameter("drugid").trim();
//		 if (StringUtils.isEmpty(drugid)) {
//			 return "managepages/error";
//			}
		 drugService.delDrugById(Integer.parseInt(drugid));
		 return new ModelAndView("redirect:/todrugmanage");
	 }
	 
	/**
	 * 跳转到修改药品页面
	 * @param request
	 * @param model
	 * @return
	 */
	 @RequestMapping(value = "/toeidtdrugbyid")
	 public String toeditdrug(HttpServletRequest request,Model model) {
		 List<Drugtype> alldrugtypes = drugTypeService.getAllDrugTyes();
		 model.addAttribute("drugtypes", alldrugtypes);
		 String drugid =  request.getParameter("drugid").trim();
		 if (StringUtils.isEmpty(drugid)) {
			 return "managepages/error";
			}
		 Drug drug = drugService.getDrugById(Integer.parseInt(drugid));
		 model.addAttribute("drug", drug);
		 return "managepages/drugmanage/toeidtdrug";
	 }
	 
	 @RequestMapping(value = "/doeidtdrug")
	 public String doEidtDrug(HttpServletRequest request,Model model) {
		Drug drug = new Drug();
		String drugid =  request.getParameter("drugid").trim();
		String drugname =  request.getParameter("drugname").trim();
		String drugtype =  request.getParameter("drugtype").trim();
		
		String netprice =  request.getParameter("netprice").trim();
		String netretailprice =  request.getParameter("netretailprice").trim();
		String topretailprice =  request.getParameter("topretailprice").trim();
		String remark =  request.getParameter("remark").trim();
		String content =  request.getParameter("content").trim();
//		String goodspic = request.getParameter("goodspic").trim();
		String norm = request.getParameter("norm").trim();
		// 获得文件：
	    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;     
        MultipartFile file = multipartRequest.getFile("pic1"); 
        String savepPicDir = request.getSession().getServletContext().getRealPath("/");
        if ((file.getSize() > 0)) {
    	   String goodspic = FileUtils.saveFile(file, "attached/drugpic", savepPicDir);
    	   drug.setGoodspic(goodspic);
        }
		
		if (StringUtils.isEmpty(netprice)) {
			netprice = "0";
		}
		if (StringUtils.isEmpty(netretailprice)) {
			netretailprice = "0";
		}
		if (StringUtils.isEmpty(topretailprice)) {
			topretailprice = "0";
		}
		
		drug.setId(Integer.parseInt(drugid));
		drug.setDrugname(drugname);
		drug.setDrugtype(Integer.parseInt(drugtype));
		drug.setNetprice(Double.valueOf(netprice));
		drug.setNetretailprice(Double.valueOf(netretailprice));
		drug.setTopretailprice(Double.valueOf(topretailprice));
		drug.setRemark(remark);
		drug.setNorm(norm);
		
		drug.setContent(content);
		drugService.updateDrugById(drug);
		
		//页面静态化处理
		//生成的文件存放在网站根目录的html/drug/类别id/
		File saveDir = new File(request.getSession().getServletContext().getRealPath(Constants.STATIC_DRUG_DIR+drug.getDrugtype()));
		BuildHtmlFile.createProductHtml(drug,"drugview.html", saveDir);
		
		 model.addAttribute("info", Constants.HANDLE_SUC);
		return "common/info";
	 }
	 
	 @RequestMapping(value = "/toadddrug")
	 public String toadddrug(HttpServletRequest request,Model model) {
		 List<Drugtype> alldrugtypes = drugTypeService.getAllDrugTyes();
		 model.addAttribute("drugtypes", alldrugtypes);
		 
		 return "managepages/drugmanage/toadddrug";
	 }
	
	 @RequestMapping(value = "/doadddrug")
	 public String doAddDrug(HttpServletRequest request,Model model) {
		Drug drug = new Drug();
		String drugname =  request.getParameter("drugname").trim();
		String drugtype =  request.getParameter("drugtype").trim();
		
		String netprice =  request.getParameter("netprice").trim();
		String netretailprice =  request.getParameter("netretailprice").trim();
		String topretailprice =  request.getParameter("topretailprice").trim();
		String remark =  request.getParameter("remark").trim();
		String content =  request.getParameter("content").trim();
		String goodspic = "";
		String norm = request.getParameter("norm").trim();
		
		 // 转型为MultipartHttpRequest：     
	//	DefaultMultipartHttpServletRequest multipartRequest= (DefaultMultipartHttpServletRequest)request;
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;     
        // 获得文件：     
//		MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
//		MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(request);
        MultipartFile file = multipartRequest.getFile("pic1"); 
        String savepPicDir = request.getSession().getServletContext().getRealPath("/");
       
        goodspic = FileUtils.saveFile(file, "attached/drugpic", savepPicDir);
 
		if (StringUtils.isEmpty(netprice)) {
			netprice = "0";
		}
		if (StringUtils.isEmpty(netretailprice)) {
			netretailprice = "0";
		}
		if (StringUtils.isEmpty(topretailprice)) {
			topretailprice = "0";
		}
		
		if (StringUtils.isEmpty(goodspic)) {
			goodspic = Constants.DEFALT_DRUG_PIC;
		}
		
		drug.setDrugname(drugname);
		drug.setDrugtype(Integer.parseInt(drugtype));
		drug.setNetprice(Double.valueOf(netprice));
		drug.setNetretailprice(Double.valueOf(netretailprice));
		drug.setTopretailprice(Double.valueOf(topretailprice));
		drug.setRemark(remark);
		drug.setNorm(norm);
		drug.setGoodspic(goodspic);
		drug.setContent(content);
		drugService.addDrug(drug);
		//页面静态化处理
		//生成的文件存放在网站根目录的html/drug/类别id/
		File saveDir = new File(request.getSession().getServletContext().getRealPath(Constants.STATIC_DRUG_DIR+drug.getDrugtype()));
		BuildHtmlFile.createProductHtml(drug,"drugview.html", saveDir);
		return "managepages/registsuccess";
	 }
	
	
	//关于法和模块
	 @RequestMapping(value = "/newcontent")
	 public String shownewscontent(HttpServletRequest request,Model model) {
		String newsid =  request.getParameter("contentid");
		News  news = newsService.getNewsById(Integer.parseInt(newsid));
		model.addAttribute("newstitle", news.getName());
		model.addAttribute("newsid", newsid);
		int parentcateid = 0;
		if (news.getCategoryid() == 4) {
			parentcateid = 4;
		} else if(news.getCategoryid() == 6){
			parentcateid = 6;
		}
		model.addAttribute("parentcateid", parentcateid);
		model.addAttribute("newscontent", news.getContent());
		return "managepages/about/toeditabout";
	 }
	 
	 
	 @RequestMapping(value = "/doeditabout")
	 public String doeditabout(HttpServletRequest request,Model model) {
		String newsid =  request.getParameter("newsid");
		News  news = new News();
		news.setId(Integer.parseInt(newsid));
		news.setName(request.getParameter("newstitle"));
		news.setContent(request.getParameter("content"));
		newsService.updateNewsById(news);
		return "managepages/registsuccess";
	 }
	 
	 
	 @RequestMapping(value = "/doeditnews")
	 public String doeditnews(HttpServletRequest request,Model model) {
		String newsid =  request.getParameter("newsid");
		News  news = new News();
		news.setId(Integer.parseInt(newsid));
		news.setName(request.getParameter("newstitle"));
		news.setContent(request.getParameter("content"));
		newsService.updateNewsById(news);
		return "managepages/registsuccess";
	 }
@RequestMapping(value = "/shownewsbycategory")
	 public String shownewsbycategory(@ModelAttribute ResultFilter<News> rf,HttpServletRequest request,Model model) {
		/*String percatid =  request.getParameter("percatid");
		String page =  request.getParameter("page");
		int pagenum = 1;
		int pagesize = 10;
		if (page != null && !"".equals(page)) {
			pagenum = Integer.parseInt(page);
		}
		List<News> allnews = newsService.selectNewsByPageAndType(Integer.parseInt(percatid),pagenum,pagesize);
		model.addAttribute("allnews", allnews);*/
		
		String categoty =  request.getParameter("categoty");
		newsService.listNews(rf,Integer.parseInt(categoty),10);
		model.addAttribute("rf", rf);
		model.addAttribute("categoty", categoty);
		return "managepages/newslist";
	 }
	 
	 @RequestMapping(value = "/toaddnews")
	 public String toaddnews(HttpServletRequest request,Model model) {
		 return "managepages/toaddnews";
	 }
	
	 @RequestMapping(value = "/doaddnews")
	 public String doaddnews(HttpServletRequest request,Model model) {
		News  news = new News();
		news.setName(request.getParameter("newstitle"));
		news.setContent(request.getParameter("content"));
		news.setCreatedate(new Date());
		news.setCategoryid(Integer.parseInt(request.getParameter("category")));
		news.setNewstype(1);
		newsService.addNews(news);
		return "managepages/newslist";
	 }
	 
	 @RequestMapping(value = "/eidtnewsbyid")
	 public String toeditnews(HttpServletRequest request,Model model) {
		String newsid =  request.getParameter("newsid");
		News  news = newsService.getNewsById(Integer.parseInt(newsid));
		model.addAttribute("newstitle", news.getName());
		model.addAttribute("newsid", newsid);
		model.addAttribute("parentcateid", news.getCategoryid());
		model.addAttribute("newscontent", news.getContent());
		 return "managepages/toeditnews";
	 }
	 
	 @RequestMapping(value = "/managehome")
	 public String tomanagehome(HttpServletRequest request) {
			if (SysContent.getRequest().getSession().getAttribute("LOGINSTATUS") != null && SysContent.getRequest().getSession().getAttribute("LOGINSTATUS").equals("1")) {
				if (SysContent.getRequest().getSession().getAttribute("level").equals("1")) {
					System.out.println("对不起你没权限");
				}else{
					 return "managepages/managehome";
				}
			}else{
				 return "login";
			}
			return null;
	 }
}
